package com.uilt;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter(value = "/*")
public class CharsetFilter implements Filter {
    //过滤器：是过滤请求的
    //拦截器：对请求进行部分拦截和放行
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("--Filterinit--");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        request.setCharacterEncoding("utf-8");
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        response.setCharacterEncoding("utf-8");
        System.out.println("doFilter");
        //登录授权（拦截请求）
        //配置放行的请求
        String path = request.getRequestURI();
        if(path.endsWith("login.jsp") || path.endsWith("login")|| path.endsWith("user")) {
          //放行
            filterChain.doFilter(request, response);
            return;
        }
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if(user ==null){
            request.getRequestDispatcher("login.jsp").forward(request,response);
            //response.sendRedirect("/login.jsp");
            return;
        }
        //放行
        filterChain.doFilter(request,response);

    }

    @Override
    public void destroy() {
        System.out.println("--destroy--");
    }

}
